package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.domain.SystemMenu;
import cn.wolfcode.wms.mapper.SystemMenuMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.qo.SystemMenuQueryObject;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.UserContext;
import cn.wolfcode.wms.vo.SystemMenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class SytemMenuService implements ISystemMenuService {





    @Autowired
    private SystemMenuMapper mapper;

    public int deleteByPrimaryKey(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    public int insert(SystemMenu systemmenu) {
        return mapper.insert(systemmenu);
    }

    public SystemMenu selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<SystemMenu> selectAll() {
        return mapper.selectAll();
    }

    public int updateByPrimaryKey(SystemMenu systemmenu) {
        return mapper.updateByPrimaryKey(systemmenu);
    }




    public void saveorupdate(SystemMenu role) {
        //
        if (role.getId() != null) {
            mapper.updateByPrimaryKey(role);
        } else {
            mapper.insert(role);
        }
}

    public void delete(Long id) {
        if(id != null){
            mapper.deleteByPrimaryKey(id);
        }


    }

    public PageResult query(SystemMenuQueryObject qo) {
       int count = mapper.queryForCount(qo);
       if(count == 0){
           return  PageResult.empty(qo.getPageSize());
       }
       List<?> list = mapper.queryForList(qo);

        PageResult pageResult = new PageResult(qo.getPageSize(), count, qo.getCurrentPage(), list);


        return pageResult;
    }

    public List<SystemMenu> getParents(Long parentId) {
        List<SystemMenu> ret = new ArrayList<>();
            //1.判断当前的parentid不为null 如果为null就表示已经获取完父节点
            SystemMenu parent = mapper.selectByPrimaryKey1(parentId);
            while (parent != null){
                ret.add(parent);

                 parent = parent.getParent();
            }
            //5.将结果完成的结果进行反转
        Collections.reverse(ret);
        return ret;
    }

    public List<SystemMenuVO> loadMenuByParentSn(String parentSn) {
        //获取当前用户
        Employee employee = UserContext.getCurrentUser();
        System.out.println(employee+"11111111111111111111111111111111111");
        //判断但前用户是否为超级管理员,如果是直接返回所有菜单
        if(employee.isAdmin()){
            return mapper.loadMenuByParentSn(parentSn);
        }
        //根据当前该用户拥有的角色去查找对应的菜单
        return mapper.loadMenuParentSnAndEmpId(parentSn,employee.getId());


    }
}

